package cn.fzkj.gulimall.product.exception;

import cn.fzkj.common.exception.ErrorsEnum;
import cn.fzkj.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @DESCRIPTION 全局异常处理
 */
@Slf4j
@RestControllerAdvice(value = "cn.fzkj.gulimall.product.controller")
public class GlobalExceptionAdvice {


    /**
     * 参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValiteException(MethodArgumentNotValidException e){
        BindingResult result = e.getBindingResult();
        if (result != null){
            Map<String, String> map = new HashMap<>();
            result.getFieldErrors().forEach(item -> {
                map.put(item.getField(), item.getDefaultMessage());
            });
            return R.error(ErrorsEnum.PARAM_VALID_FAILD).put("data", map);
        }
        return R.error();
    }

    /**
     * 通用异常
     */
    @ExceptionHandler(value = Exception.class)
    public R handleException(Exception e){
        log.warn("统一异常处理捕获异常 -> {}, 异常消息 -> {}", e.getClass(), e);
        return R.error(ErrorsEnum.UNKOWN_EXCEPTION);
    }

}
